class CommentsController < ApplicationController
	before_filter :require_login, except: [:create]
  before_filter :load_commentable, except: [:preview]

  def index
    @comments = @commentable.comments
  end

	def new
    @comment = @commentable.comments.new
	end

	def create
    @comment = @commentable.comments.new(comment_params)
    @commentable = Article.find(params[:article_id])  #要設置這個不然save失敗會變nil
    if @comment.save
       redirect_to @commentable
    else
       render 'articles/show'
    end
	end

  def preview
    @content = params[:content]
    respond_to do |format|
      format.js
    end
  end

	private

	def comment_params
		params.require(:comment).permit(:author_name, :body)
	end

	def load_commentable
        resource, id = request.path.split('/')[1, 2]
        @commentable = resource.singularize.classify.constantize.find(id)
  end

end
